package com.rbs.controller;

import com.alipay.api.AlipayApiException;
import com.rbs.service.OrderService;
import com.rbs.util.AlipayTemplate;
import com.rbs.util.PayVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
@RequestMapping("/ali")
public class PayController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private AlipayTemplate alipayTemplate;
    @RequestMapping("/pay")
    public void pay(HttpServletResponse response,String orderId,String amount) throws IOException, AlipayApiException {
        //设置响应格式
        response.setContentType("text/html;charset=UTF-8");
        /**
         *     private String out_trade_no; // 商户订单号 必填
         *     private String subject; // 订单名称 必填
         *     private String total_amount;  // 付款金额 必填
         *     private String body; // 商品描述 可空
         */
        PayVo payVo = new PayVo();
        payVo.setOut_trade_no(orderId);
        payVo.setTotal_amount(amount);
        payVo.setBody("当当网支付");
        payVo.setSubject("支付页面");

        //发送支付请求
        //返回值是支付的二维码页面，将此页面展示到浏览器上
        String pay = alipayTemplate.pay(payVo);

        //通过response对象将内容展示到页面上
        PrintWriter writer = response.getWriter();
        writer.println(pay);
    }
    @RequestMapping("/orderPayed")
    public String orderPayed(int out_trade_no, HttpServletRequest request){
        //返回值为true和false
        //true 支付宝发送的请求
        //false 别人发送的请求
        boolean b = alipayTemplate.rsaCheckV1(request);
        if (b){
            //执行修改
            orderService.orderPayed(out_trade_no);
        }
        //查询订单
        return "redirect:/order/selectByUserId.do";
    }
}
